﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using BlogsAPI.Abstract;
using Newtonsoft.Json.Linq;

namespace BlogsAPI.Images
{
    /// <summary>
    /// Популярный мобильный gif-хостинг
    /// </summary>
    [SingleImager(Link = "https://vine.co")]
    public class Vine : ImageServer
    {
        /// <summary>
        /// Получение превьюшки 
        /// </summary>
        /// <param name="sLink"></param>
        /// <returns></returns>
        public override string GetThumb(string sLink)
        {
            string MediaLinked = String.Empty;
            //https://vine.co/oembed.json?url=https%3A%2F%2Fvine.co%2Fv%2FMl16lZVTTxe
            try
            {
  //{
  //"version": 1.0,
  //"type": "video",
  //"cache_age": 3153600000,
  //"provider_name": "Vine",
  //"provider_url": "https://vine.co/",
  //"author_name": "The White House",
  //"author_url": "https://vine.co/u/944054069482373120",
  //"title": "Marine One, ready for takeoff. \ud83d\ude81",
  //"thumbnail_url": "https://v.cdn.vine.co/r/thumbs/3A1E5CC27C1116110482407841792_2.5.1.13603721890676705621.mp4.jpg?versionId=_B5dDtCI.ZNd_JLK_.sFmfpQq44iXdey",
  //"thumbnail_width": 480,
  //"thumbnail_height": 480,
  //"html": "<iframe class=\"vine-embed\" src=\"https://vine.co/v/Ml16lZVTTxe/embed/simple\" width=\"600\" height=\"600\" frameborder=\"0\"><\/iframe><script async src=\"//platform.vine.co/static/scripts/embed.js\"><\/script>",
  //"width": 600,
  //"height": 600
  //}
                var client = new WebClient();
                Stream stream = client.OpenRead(String.Format("https://vine.co/oembed.json?url={0}", HttpUtility.UrlEncode(sLink)));
                var reader = new StreamReader(stream);
                JToken token = JObject.Parse(reader.ReadToEnd());
                
                
                UserName = token["author_name"].Value<string>();//+
                MediaID = "";          
                Height = token["thumbnail_height"].Value<string>();//+
                Width = token["thumbnail_width"].Value<string>();//+
                Title = token["title"].Value<string>();//+
                //can be empty???
                MediaLinked = token["thumbnail_url"].Value<string>();//+
                UserID = token["author_url"].Value<string>().Split('/').Last();//+
            }
            catch (Exception e1)
            {
                Debug.WriteLine(e1.Message);
            }
            return MediaLinked;
        }
    }
}
